<?php

class OpenidComponent extends Object
{
	var $controller = null;
	var $_error;
	var $components = array('Session');
	
	function startUp(&$controller)
	{
		$this->controller = $controller;
		$pathExtra = APP.DS.'vendors'.DS.PATH_SEPARATOR.VENDORS;
		$path = ini_get('include_path');
		$path = $pathExtra . PATH_SEPARATOR . $path;
		ini_set('include_path', $path);
	}
	
	function authenticate($openId, $processUrl, $trustRoot, $extensionArguments = null)
	{
		$consumer = $this->__getConsumer();
		$ret = $consumer->checkid_setup($openId, $processUrl, $trustRoot);
		
		if(!$ret)
		{
			$this->Session->write('service_url', $consumer->getServiceUrl());
			$this->Session->write('openid_url', $openId);
			$this->controller->redirect($consumer->getRedirectUrl());
			return true;
		}
		else
		{
			$_error = $ret;
			return false;
		}
	}
	
	function getResponse()
	{
		$consumer = $this->__getConsumer();
		$ret = $consumer->check_authentication($this->Session->read('service_url'));
		
		if(!$ret)
		{
			$this->Session->delete('service_url');
			$url = $this->Session->read('openid_url');
			$this->Session->delete('openid_url');
			//return $consumer->getIdentity();
			return $url;
		}
		
		$_error = $ret;
		return false;
	}
	
	function getError()
	{
		return $this->_error;
	}
	
	function __getConsumer()
	{
		App::import('Vendor', 'openid');
		return new OpenID();
	}
	
	function sanitize($url)
	{
		$url = ereg_replace('http(s?)://', '', trim($url));
		
		if(strpos($url, '/') == strlen($url) - 1)
			$url = substr($url, 0, -1);
		
		return $url;
	}
}

?>
